package com.baijiayun.liveuibase.utils;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import androidx.annotation.AttrRes;
import androidx.annotation.ColorInt;
import androidx.core.content.ContextCompat;
import android.text.TextUtils;
import android.util.TypedValue;

import com.baijiayun.livecore.models.launch.CustomColor;
import com.baijiayun.livecore.utils.LPLogger;
import com.baijiayun.liveuibase.R;
import com.baijiayun.liveuibase.utils.drawable.DrawableBuilder;

import java.util.HashMap;
import java.util.Map;

public class ThemeDataUtil {

    /**
     * 配置项颜色： key - attr id、 value - 对应 int color 值
     */
    private static HashMap<Integer, Integer> themeConfig;

    public static HashMap<Integer, Integer> getThemeConfig() {
        return themeConfig;
    }

    public static void initThemeConfig(CustomColor customColor) {
        if (customColor == null) {
            return;
        }
        if (themeConfig == null) {
            themeConfig = new HashMap<>();
        } else {
            themeConfig.clear();
        }
        putColor2ThemeConfig(R.attr.base_theme_live_product_color, customColor.productColor);
        putColor2ThemeConfig(R.attr.base_theme_window_bg_color, customColor.windowBgColor);
        customColor.brandContainerColor = customColor.windowBgColor.replace("#", "#E6");
        putColor2ThemeConfig(R.attr.base_theme_brand_container_color, customColor.brandContainerColor);
        putColor2ThemeConfig(R.attr.base_theme_room_bg_color, customColor.roomBgColor);
        putColor2ThemeConfig(R.attr.base_theme_blackboard_color, customColor.blackboardColor);
        putColor2ThemeConfig(R.attr.base_theme_bottom_menu_text_color, customColor.bottomMenuTextColor);
        putColor2ThemeConfig(R.attr.base_theme_window_main_text_color, customColor.mainTextColor);
        putColor2ThemeConfig(R.attr.base_theme_window_assistant_text_color, customColor.assistantTextColor);
        putColor2ThemeConfig(R.attr.base_theme_dialog_negative_bg_color, customColor.negativeBgColor);
        putColor2ThemeConfig(R.attr.base_theme_dialog_negative_text_color, customColor.negativeTextColor);
        putColor2ThemeConfig(R.attr.base_theme_dialog_positive_text_color, customColor.positiveTextColor);
    }

    /**
     * 退教室的时候需要调用这个方法清理一下数据，否则如果新的教室没有配置皮肤，那依然会使用上个教室的皮肤值
     */
    public static void clearConfig() {
        if (themeConfig != null) {
            themeConfig.clear();
        }
    }

    private static void putColor2ThemeConfig(@AttrRes int attrId, String colorString) {
        if (TextUtils.isEmpty(colorString) || !colorString.contains("#")) {
            return;
        }
        themeConfig.put(attrId, Color.parseColor(colorString));
    }

    /**
     * 按 attr 值获取对应的配置项颜色
     *
     * @param attrId attr值
     * @return 返回结果色值，如果已有配置项，则返回对应的配置项色值，否则返回当前默认 theme 对应色值
     */
    public static int getColorFromThemeConfigByAttrId(Context context, int attrId) {
        int defaultColor = getColorByAttributeId(context, attrId);
        if (themeConfig == null) {
            return defaultColor;
        }
        Integer color = themeConfig.get(attrId);
        return color == null ? defaultColor : color;
    }

    /**
     * 按 attr 值获取对应的配置项颜色并修改 alpha 值
     *
     * @param attrId attr值
     * @param a      设置 alpha 透明度
     * @return 返回结果色值，如果已有配置项，则返回对应的配置项 alpha 色值，否则返回当前默认 theme 对应色值 并设置 alpha
     */
    public static int getColorFromThemeConfigByAttrIdWithAlpha(Context context, int attrId, float a) {
        int color = getColorFromThemeConfigByAttrId(context, attrId);
        float r = ((color >> 16) & 0xff) / 255.0f;
        float g = ((color >> 8) & 0xff) / 255.0f;
        float b = ((color) & 0xff) / 255.0f;
        a = Math.max(0f, Math.min(1f, a));
        return ((int) (a * 255.0f + 0.5f) << 24) |
                ((int) (r * 255.0f + 0.5f) << 16) |
                ((int) (g * 255.0f + 0.5f) <<  8) |
                (int) (b * 255.0f + 0.5f);
    }

    private static int getColorByAttributeId(Context context, int attrId) {
        try {
            TypedValue typedValue = new TypedValue();
            Resources.Theme theme = context.getTheme();
            theme.resolveAttribute(attrId, typedValue, true);
            return typedValue.data;
        } catch (Exception e) {
            LPLogger.e("颜色没找到！" + attrId);
            return Color.TRANSPARENT;
        }
    }

    public static @ColorInt
    int getColorFromThemConfigByColorId(Context context, int colorId) {
        if (themeConfig == null) {
            return ContextCompat.getColor(context, colorId);
        }
        for (Map.Entry<Integer, Integer> entry : themeConfig.entrySet()) {
            int key = entry.getKey() == null ? 0 : entry.getKey();
            int value = entry.getValue() == null ? 0 : entry.getValue();
            if (colorId == getResIdByAttributeId(context, key)) {
                return value;
            }
        }
        @ColorInt int color = Color.RED;
        try {
            color = ContextCompat.getColor(context, colorId);
        } catch (Exception e) {
            LPLogger.e("(" + colorId + ") 不是 color res id");
            e.printStackTrace();
        }
        return color;
    }

    private static int getResIdByAttributeId(Context context, int attrId) {
        TypedValue typedValue = new TypedValue();
        Resources.Theme theme = context.getTheme();
        theme.resolveAttribute(attrId, typedValue, true);
        return typedValue.resourceId;
    }

    // region 换肤通用 drawable 生成

    /**
     * 通用换肤 window bg
     * 纯色 base_theme_window_bg_color；圆角 base_common_bg_radius
     */
    public static Drawable getCommonWindowBg(Context context) {
        return context == null ? null : new DrawableBuilder()
                .solidColor(getColorFromThemeConfigByAttrId(context, R.attr.base_theme_window_bg_color))
                .cornerRadius(context.getResources().getDimensionPixelSize(R.dimen.bjy_base_common_bg_radius))
                .build();
    }

    /**
     * 通用换肤 window bg
     * 纯色 base_theme_window_bg_color；圆角 base_common_bg_radius
     */
    public static Drawable getCommonWindowBgWithBorder(Context context) {
        return context == null ? null : new DrawableBuilder()
                .solidColor(getColorFromThemeConfigByAttrId(context, R.attr.base_theme_window_bg_color))
                .cornerRadius(context.getResources().getDimensionPixelSize(R.dimen.bjy_base_common_bg_radius))
                .strokeWidth(1)
                .strokeColor(ContextCompat.getColor(context, R.color.base_bg_stroke))
                .build();
    }

    /**
     * 通用产品色 button 背景 drawable
     * 纯色 productColor；圆角 base_common_bg_radius
     */
    public static Drawable getDrawableProductButtonBg(Context context) {
        return context == null ? null : new DrawableBuilder()
                .solidColor(getColorFromThemeConfigByAttrId(context, R.attr.base_theme_live_product_color))
                .cornerRadius(context.getResources().getDimensionPixelSize(R.dimen.bjy_base_common_bg_radius))
                .build();
    }

    /**
     * 通用产品色 button 背景 drawable
     * 纯色 productColor；圆角 base_common_bg_radius
     */
    public static Drawable getDrawableNegativeButtonBg(Context context) {
        return context == null ? null : new DrawableBuilder()
                .solidColor(getColorFromThemeConfigByAttrId(context, R.attr.base_theme_dialog_negative_bg_color))
                .cornerRadius(context.getResources().getDimensionPixelSize(R.dimen.bjy_base_common_bg_radius))
                .build();
    }

    /**
     * 老师 or 助教 标签背景
     * 蓝色一像素边框 圆角 base_common_bg_radius
     */
    public static Drawable getUserTagBg(Context context) {
        return context == null ? null : new DrawableBuilder()
                .cornerRadius(context.getResources().getDimensionPixelSize(R.dimen.bjy_base_common_bg_radius))
                .strokeColor(getColorFromThemeConfigByAttrId(context, R.attr.base_theme_live_product_color))
                .strokeWidth(DisplayUtils.dip2px(context, 1))
                .build();
    }

    /**
     * 通用产品色按钮样式，圆角 2/4 dp，enable - 产品色，unEnable - negativeBgColor
     */
    public static Drawable getEnableProductBgWithCorner(Context context) {
        return context == null ? null : new DrawableBuilder()
                .solidColorStateList(getColorEnableProduct2NegativeBG(context))
                .cornerRadius(context.getResources().getDimensionPixelSize(R.dimen.bjy_base_common_bg_radius))
                .build();
    }
    // endregion

    // region 换肤通用 state color 生成

    /**
     * selector 颜色。变更属性：check，颜色：{check:白色, unCheck:主文字颜色}
     *
     * @param context 上下文
     */
    public static ColorStateList getColorCheckWhite2MainText(Context context) {
        if (context == null) {
            return new ColorStateList(new int[][]{}, new int[]{Color.TRANSPARENT});
        }
        return new ColorStateList(new int[][]{
                new int[]{android.R.attr.state_checked},
                new int[]{-android.R.attr.state_checked},
        }, new int[]{
                ContextCompat.getColor(context, R.color.base_white),
                getColorFromThemeConfigByAttrId(context, R.attr.base_theme_window_main_text_color)
        });
    }

    /**
     * selector 颜色。变更属性：select，颜色：{select:主题色, unSelect:主文字颜色}
     *
     * @param context 上下文
     */
    public static ColorStateList getColorSelectProduct2MainText(Context context) {
        if (context == null) {
            return new ColorStateList(new int[][]{}, new int[]{Color.TRANSPARENT});
        }
        return new ColorStateList(new int[][]{
                new int[]{android.R.attr.state_selected},
                new int[]{-android.R.attr.state_selected},
        }, new int[]{
                getColorFromThemeConfigByAttrId(context, R.attr.base_theme_live_product_color),
                getColorFromThemeConfigByAttrId(context, R.attr.base_theme_window_main_text_color)
        });
    }

    /**
     * selector 颜色。变更属性：select，颜色：{select:白色, unSelect:主文字颜色}
     *
     * @param context 上下文
     */
    public static ColorStateList getColorSelectWhite2MainText(Context context) {
        if (context == null) {
            return new ColorStateList(new int[][]{}, new int[]{Color.TRANSPARENT});
        }
        return new ColorStateList(new int[][]{
                new int[]{android.R.attr.state_selected},
                new int[]{-android.R.attr.state_selected},
        }, new int[]{
                ContextCompat.getColor(context, R.color.base_white),
                getColorFromThemeConfigByAttrId(context, R.attr.base_theme_window_main_text_color)
        });
    }

    /**
     * selector 颜色。变更属性：enable，颜色：{enable:主文字颜色, unEnable:警告色}
     *
     * @param context 上下文
     */
    public static ColorStateList getColorEnableMainText2Warning(Context context) {
        if (context == null) {
            return new ColorStateList(new int[][]{}, new int[]{Color.TRANSPARENT});
        }
        return new ColorStateList(new int[][]{
                new int[]{android.R.attr.state_enabled},
                new int[]{-android.R.attr.state_enabled},
        }, new int[]{
                getColorFromThemeConfigByAttrId(context, R.attr.base_theme_window_main_text_color),
                ContextCompat.getColor(context, R.color.base_warning_color)
        });
    }

    /**
     * selector 颜色。变更属性：select，颜色：{select:产品色, unSelect:negative_bg_color}
     *
     * @param context 上下文
     */
    public static ColorStateList getColorEnableProduct2NegativeBG(Context context) {
        if (context == null) {
            return new ColorStateList(new int[][]{}, new int[]{Color.TRANSPARENT});
        }
        return new ColorStateList(new int[][]{
                new int[]{android.R.attr.state_enabled},
                new int[]{-android.R.attr.state_enabled},
        }, new int[]{
                getColorFromThemeConfigByAttrId(context, R.attr.base_theme_live_product_color),
                getColorFromThemeConfigByAttrId(context, R.attr.base_theme_dialog_negative_bg_color),
        });
    }

    /**
     * selector 颜色。变更属性：select，颜色：{select:产品色, unSelect:negative_bg_color}
     *
     * @param context 上下文
     */
    public static ColorStateList getColorEnableWhite2NegativeText(Context context) {
        if (context == null) {
            return new ColorStateList(new int[][]{}, new int[]{Color.TRANSPARENT});
        }
        return new ColorStateList(new int[][]{
                new int[]{android.R.attr.state_enabled},
                new int[]{-android.R.attr.state_enabled},
        }, new int[]{
                ContextCompat.getColor(context, R.color.base_white),
                getColorFromThemeConfigByAttrId(context, R.attr.base_theme_dialog_negative_text_color),
        });
    }
    // endregion
}
